#include "apputil.h"
#include <QDir>
#include "appsettings.h"
#include <QFileDialog>
#include <QDateTime>



AppUtil::AppUtil()
{

}


QString AppUtil::getDefSnapDir()
{
    QString rootDir = QApplication::applicationDirPath();
    rootDir += QDir::separator();
    rootDir += "snap";
    return rootDir;
}

QString AppUtil::getDefCutDir()
{
    QString rootDir = QApplication::applicationDirPath();
    rootDir += QDir::separator();
    rootDir += "cut";
    return rootDir;
}


QString AppUtil::getSnapDir()
{
    QString snapDir = AppSettings::getString("App/SnapDir", AppUtil::getDefSnapDir());
    QDir dir(snapDir);
    if (!dir.exists())
    {
        dir.mkpath(".");
    }
    return dir.canonicalPath();
}

QString AppUtil::getCutDir()
{
    QString cutDir = AppSettings::getString("App/cutDir", AppUtil::getDefCutDir());
    QDir dir(cutDir);
    if (!dir.exists())
    {
        dir.mkpath(".");
    }
    return dir.canonicalPath();
}

bool AppUtil::chooseFolder(QString& dir)
{
	bool found = false;
	QFileDialog dialog;
	QString path = QFileDialog::getExistingDirectory(nullptr, "", "", QFileDialog::ShowDirsOnly);
	if (!path.isEmpty())
	{
		dir = path;
		found = true;
	}

	return found;
}

QString AppUtil::makeCutFileName()
{
    QDateTime dt = QDateTime::currentDateTime();
    QString timePart = dt.toString("yyyyMMdd-hhmmss");
    QString fileName = timePart;// + ".mp4";
    return fileName;
}

QString AppUtil::makeSnapFileName()
{
    QDateTime dt = QDateTime::currentDateTime();
    QString timePart = dt.toString("yyyyMMdd-hhmmss");
    QString fileName = timePart + ".jpg";
    return fileName;
}

QString AppUtil::makeSnapFilePath()
{
    QString snapDir = getSnapDir();
    QDir dir(snapDir);
    if (!dir.exists())
    {
        dir.mkpath(".");
    }

    return dir.absoluteFilePath(makeSnapFileName());
}

QString AppUtil::makeCutFilePath(const QString& title)
{
    QDir dir(getCutDir());
    if (!dir.exists())
    {
        dir.mkpath(".");
    }
    return dir.absoluteFilePath(title + ".mp4");
}

QStringList AppUtil::listDir(const QString& filepath)
{
    QDir dir(filepath);
    QStringList filters;
    filters << "*.mp4";
    return dir.entryList(filters, QDir::Files);
}

QString AppUtil::getChannel(const QString& filename)
{
    return filename.mid(0, 2);
}

QStringList AppUtil::getChannels(const QStringList& fileList)
{
    QStringList chlList;
    for (int i = 0; i < fileList.size(); i++)
    {
        QString chl = getChannel(fileList[i]);
        if (!chlList.contains(chl))
        {
            chlList.push_back(chl);
        }
    }
    return chlList;
}

QString AppUtil::formatSeconds(int seconds)
{
    int minutes = seconds / 60;
    int sec = seconds % 60;
    return QString("%1:%2").arg(minutes, 2, 10, QLatin1Char('0')).arg(sec, 2, 10, QLatin1Char('0'));
}
